package com.ljx.funchat.chat.service.adapter;

import com.ljx.funchat.chat.domain.entity.Message;
import com.ljx.funchat.chat.domain.enums.MessageStatusEnum;
import com.ljx.funchat.chat.domain.enums.MessageTypeEnum;
import com.ljx.funchat.chat.domain.vo.req.ChatMessageReq;
import com.ljx.funchat.chat.domain.vo.req.TextMsgReq;
import com.ljx.funchat.chat.domain.vo.resp.ChatMessageResp;
import com.ljx.funchat.chat.service.strategy.AbstractMsgHandler;
import com.ljx.funchat.chat.service.strategy.MsgHandlerFactory;
import com.ljx.funchat.common.utils.RequestHolder;
import com.ljx.funchat.websocket.domain.vo.resp.WSMessage;
import org.checkerframework.checker.units.qual.C;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class MessageAdapter {

    public static List<ChatMessageResp> buildMsgResp(List<Message> messages, Long receiveUid, Long uid) {
        return messages.stream().map(a -> {
            ChatMessageResp resp = new ChatMessageResp();
            resp.setFromUser(buildFromUser(a.getFromUid()));
            resp.setMessage(buildMessage(a, receiveUid, uid));
            return resp;
        }).sorted(Comparator.comparing(a -> a.getMessage().getSendTime()))//帮前端排好序，更方便它展示
          .collect(Collectors.toList());
    }

    private static WSMessage.Message buildMessage(Message message, Long receiveUid, Long uid) {
        WSMessage.Message res = new ChatMessageResp.Message();
        res.setId(message.getId());
        res.setRoomId(message.getRoomId());
        res.setSendTime(message.getCreateTime());
        res.setType(message.getType());
        AbstractMsgHandler<?> msgHandler = MsgHandlerFactory.getStrategyNoNull(message.getType());
        if (Objects.nonNull(msgHandler)) {
            res.setBody(msgHandler.showMsg(message, uid));
        }
        return res;
    }

    private static WSMessage.UserInfo buildFromUser(Long fromUid) {
        ChatMessageResp.UserInfo userInfo = new ChatMessageResp.UserInfo();
        userInfo.setUid(fromUid);
        return userInfo;
    }

    public static Message buildMsgSave(ChatMessageReq request, Long uid) {
        Message message = new Message();
        message.setRoomId(request.getRoomId());
        message.setType(request.getMsgType());
        message.setFromUid(uid);
        message.setStatus(MessageStatusEnum.NORMAL.getStatus());
        return message;
    }

    public static ChatMessageReq buildAgreeMsg(Long roomId, Long uid) {
        TextMsgReq textMsgReq = new TextMsgReq();
        textMsgReq.setContent("我们已经成为好友了，开始聊天吧");
        ChatMessageReq req = new ChatMessageReq();
        req.setRoomId(roomId);
        req.setMsgType(MessageTypeEnum.TEXT.getType());
        req.setBody(textMsgReq);
        return req;
    }
}
